import datastructure.linklist.ListNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/11 10:21
 * @description:
 */
public class Solution83 {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode noEquals = head;  // 记录不重复的节点（慢指针）
        ListNode current = head.next;  // 当前遍历的节点（快指针）

        while (current != null) {
            if (noEquals.val != current.val) {
                // 找到不重复元素，移动noEquals并连接
                noEquals.next = current;
                noEquals = current;
            }
            // 无论是否重复，current都向后移动
            current = current.next;
        }

        // 关键修复：截断链表，避免末尾残留重复元素
        noEquals.next = null;

        return head;
    }
    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode current = head;
        while (current.next != null) {
            if (current.val == current.next.val) {
                current.next=current.next.next;
            }
            current = current.next;
        }
        return head;
    }
    public static void main(String[] args) {
        ListNode head = ListNode.arrayToList(new int[]{1, 1, 2, 3, 3, 4, 4, 5, 5});
        Solution83 solution = new Solution83();
        ListNode newHead = solution.deleteDuplicates(head);
        ListNode.printList(newHead);
    }
}
